package com.ckb.gulimall.product.service.impl;

import com.ckb.common.utils.Constant;
import com.ckb.common.utils.RedisKeys;
import com.ckb.gulimall.product.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ckb.common.utils.PageUtils;
import com.ckb.common.utils.Query;

import com.ckb.gulimall.product.dao.CategoryDao;
import com.ckb.gulimall.product.entity.CategoryEntity;
import com.ckb.gulimall.product.service.CategoryService;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private RedisUtils redisUtils;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    // 树形分类列表
    @Override
    public List<CategoryEntity> listWithTree() {
        // 所有列表集合
        List<CategoryEntity> entities = baseMapper.selectList(null);

        // 查找所有一级分类
        return cacheData(entities
                .stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek((menu) -> menu.setChildren(getChildren(menu, entities)))
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList()));
    }

    /**
     * 数据缓存
     * @param data
     * @return
     */
    private List<CategoryEntity> cacheData(List<CategoryEntity> data) {
        String productCategoryKey = RedisKeys.getProductCategoryKey("list");
        if (!CollectionUtils.isEmpty(data)) {
            List<CategoryEntity> cacheList = redisUtils.get(productCategoryKey, List.class);
            if (!CollectionUtils.isEmpty(cacheList)) {
                return cacheList;
            }
            redisUtils.set(productCategoryKey, data);
            return data;
        }
        return null;
    }

    // 查找所有菜单的子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {

        return all
                .stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .peek(categoryEntity -> {
                    // 找到子菜单
                    categoryEntity.setChildren(getChildren(categoryEntity, all));
                })
                .sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort())))
                .collect(Collectors.toList());
    }

    @Override
    public void removeMenusByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单,是否被别的地方引用
        // 逻辑删除
        baseMapper.deleteBatchIds(asList);
        redisUtils.delete(RedisKeys.getProductCategoryKey("list"));
    }

    @Override
    public void saveCategory(CategoryEntity category) {
        baseMapper.insert(category);
        redisUtils.delete(RedisKeys.getProductCategoryKey("list"));
    }

    @Override
    public void updateCategoryById(CategoryEntity category) {
        baseMapper.updateById(category);
        redisUtils.delete(RedisKeys.getProductCategoryKey("list"));
    }
}